import api from "@/api/api";
export default {
  state: {
    userInfo: {},
    token: {},
    fresh: {},
    power: {},
    power_user: {}
  },
  mutations: {
    userInfo (state, res) {
      state.userInfo = res;
    },
    token (state, res) {
      state.token = res;
    },
    fresh (state, res) {
      state.fresh = res;
    },
    power (state, res) {
      state.power = res;
    },
    power_user (state, res) {
      state.power_user = res;
    }
  },
  getters: {},
  actions: {
    userInfo ({ commit }, obj) {
      return new Promise((resolve, reject) => {
        api.login(obj).then(res => {
          if (res.code === "0") {
            localStorage.setItem("user_id", res.data.user_id);
            localStorage.setItem("role", res.data.username);
            localStorage.setItem("user_name", res.data.realname);
            // localStorage.setItem("token", res.data.mob_token);

            resolve(res);
          } else {
            reject();
          }
        });
      });
    },
    token ({ commit }, obj) {
      return new Promise((resolve, reject) => {
        api.roleLogin(obj).then(res => {
          if (res.code == "0") {
            localStorage.setItem("token", res.data.token);
            //console.log(res.data.token);
            //console.log(localStorage.getItem("token"));
            resolve(res);
          } else {
            reject();
          }
        });
      });
    },
    getUserInfo ({ commit }) {
      return api
        .getUser({
          params: {
            who_am_i: 1
          }
        })
        .then(res => {
          commit("userInfo", res);
        });
    },
    fresh ({ commit }) {
      return new Promise(resolve => {
        api.fresh().then(res => {
          commit("fresh", res);
          resolve(res);
        });
      });
    },
    power ({ commit }) {
      return new Promise(resolve => {
        // getPrivilege
        api.getPrivilege().then(res => {
          commit("power", res);
          resolve(res);
        });
      });
    },
    power_user ({ commit }) {
      return new Promise(resolve => {
        api
          .getUserPrivilege({
            params: {
              user_id: localStorage.getItem("user_id")
            }
          })
          .then(res => {
            commit("power_user", res);
            resolve(res);
          });
      });
    }
  }
};
